﻿using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using Hongsh.Pay.Client;
using MapleLeaf.Pay.Pay;
using MapleLeaf.Pay.Trade;

namespace MapleLeaf.Client.Pages {
    /// <summary>
    /// CashPage.xaml 的交互逻辑
    /// </summary>
    public partial class CashPage : Page {
        public CashPage() {
            DataContext = HongshPayClientContext.Default;
            InitializeComponent();
            Application.Current.MainWindow.PreviewKeyDown += MainWindow_PreviewKeyDown;
            Timer = new System.Timers.Timer(200.0);
            Timer.Elapsed += Timer_Elapsed;
            CashingFateIn = CashingGrid.FadeIn(200, 0);
            CashingFateOut = CashingGrid.FadeOut(200, 0);
            Loaded += CahierPage_Loaded;
        }

        private void CahierPage_Loaded(object sender, RoutedEventArgs e) {
            AmountInput.Focus();
        }

        private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e) {
            if (e.Key == Key.Escape) {
                if (CashingGrid.IsVisible) {
                    StopCashing(null, null);
                }
                else {
                    Application.Current.MainWindow.Hide();
                }
            }
            else if (e.Key == Key.End && IsVisible) {
                ShiftButton_Click(null, null);
            }
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e) {
            HongshPayClientContext.Default.CashTime -= (int)Timer.Interval;
            if (HongshPayClientContext.Default.CashTime <= 0) {
                Timer.Stop();
                _ = Dispatcher.Invoke(new Action(delegate () {
                    CashingFateOut.Begin();
                    _ = AmountInput.Focus();
                }), new object[0]);
            }
        }

        private void InputBox_GetFocus(object sender, RoutedEventArgs e) {
            (sender as TextBox).SelectAll();
        }


        private void AmountInput_KeyDown(object sender, KeyEventArgs e) {
            if (e.Key == Key.Return) {
                _ = AuthcodeInput.Focus();
            }
        }


        private void AuthcodeInput_KeyDown(object sender, KeyEventArgs e) {

            if (e.Key == Key.Return) {
                if (HongshPayClientContext.Default.CashAmount == 0 || HongshPayClientContext.Default.CashAuthcode.Length <= 0) {
                    _ = AmountInput.Focus();
                }
                else {
                    BeginCashing();
                }
            }
        }

        private void NumberButton_Click(object sender, RoutedEventArgs e) {
            IInputElement focusedElement = FocusManager.GetFocusedElement(Application.Current.MainWindow);
            if (focusedElement != null) {
                TextComposition composition = new TextComposition(InputManager.Current, focusedElement, (string)((Button)sender).Content);
                TextCompositionEventArgs e2 = new TextCompositionEventArgs(Keyboard.PrimaryDevice, composition) {
                    RoutedEvent = TextInputEvent
                };
                focusedElement.RaiseEvent(e2);
            }
        }


        private void PayButton_Click(object sender, RoutedEventArgs e) {
            BeginCashing();
        }


        private void ShiftButton_Click(object sender, RoutedEventArgs e) {
        }

        private void BeginCashing() {
            HongshPayClientContext.Default.CashTime = (HongshPayClientContext.Default.Config.HttpTimeout + HongshPayClientContext.Default.Config.TradeDuration) * 1000;
            HongshPayClientContext.Default.CashState = TradeState.未知;
            HongshPayClientContext.Default.CashStateDescript = "交易创建中";
            CashingFateIn.Begin();
            new Task(new Action(Cashing)).Start();
        }

        private void Cashing() {
            Timer.Start();
            try {
                string cashAuthcode = HongshPayClientContext.Default.CashAuthcode;
                HongshPayClientContext.Default.CashAuthcode = "";
                if (HongshPayClientContext.Default.CashAmount == 0) {
                    throw new Exception("无效的付款金额");
                }
                if (TradeAuthPaymentRequest.AuthcodeGetTradePayway(cashAuthcode) == TradePayway.未知) {
                    throw new Exception("无效的付款码");
                }
                HongshPayTrade hongshPayTrade = HongshPayClientContext.Default.TradeManager.Execute(new TradeAuthPaymentRequest {
                    Amount = HongshPayClientContext.Default.CashAmount,
                    Authcode = cashAuthcode,
                    ClientName = App.ProductName
                });
                TradePaymentQueryRequest req = new TradePaymentQueryRequest {
                    TradeId = hongshPayTrade.TradeId,
                    ClientTradeId = hongshPayTrade.ClientTradeId
                };
                int cashTime = HongshPayClientContext.Default.CashTime;
                int num = HongshPayClientContext.Default.Config.HttpTimeout + HongshPayClientContext.Default.Config.TradeResultStay;
                do {
                    if (cashTime - HongshPayClientContext.Default.CashTime > 3500) {
                        HongshPayClientContext.Default.CashStateDescript = "查询中";
                        hongshPayTrade = HongshPayClientContext.Default.TradeManager.Execute(req);
                        cashTime = HongshPayClientContext.Default.CashTime;
                    }
                    TradeState state = hongshPayTrade.State;
                    TradeState tradeState = state;
                    if (tradeState != TradeState.成功) {
                        if (tradeState - TradeState.关闭 > 1) {
                            Thread.Sleep(100);
                            HongshPayClientContext.Default.CashStateDescript = (!string.IsNullOrEmpty(hongshPayTrade.StateDescript)) ? hongshPayTrade.StateDescript : "交易处理中";
                        }
                        else {
                            HongshPayClientContext.Default.CashState = TradeState.失败;
                            HongshPayClientContext.Default.CashStateDescript = (!string.IsNullOrEmpty(hongshPayTrade.StateDescript)) ? hongshPayTrade.StateDescript : "交易失败";
                        }
                    }
                    else {
                        HongshPayClientContext.Default.CashAmountString = string.Empty;
                        HongshPayClientContext.Default.CashState = TradeState.成功;
                        HongshPayClientContext.Default.CashStateDescript = string.Format("交易成功，{0} 收款 {1:0.00} 元！", hongshPayTrade.Payway, hongshPayTrade.Amount / 100.0);
                    }
                }
                while (hongshPayTrade.State == TradeState.未知 && HongshPayClientContext.Default.CashTime > num);
            }
            catch (Exception ex) {
                HongshPayClientContext.Default.CashState = TradeState.失败;
                HongshPayClientContext.Default.CashStateDescript = ex.Message;
            }
            if (HongshPayClientContext.Default.CashTime > HongshPayClientContext.Default.Config.TradeResultStay * 1000) {
                HongshPayClientContext.Default.CashTime = HongshPayClientContext.Default.Config.TradeResultStay * 1000;
            }
        }


        private void StopCashing(object sender, RoutedEventArgs e) {
            HongshPayClientContext.Default.CashTime = 0;
        }


        public readonly System.Timers.Timer Timer;


        public readonly Storyboard CashingFateIn;


        public readonly Storyboard CashingFateOut;
    }
}
